<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>会员中心-公众号管理</title>
    <!-- 引入 Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- 引入 Font Awesome 图标 -->
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <!-- 引入 jQuery -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <!-- 引入公众号授权相关功能 -->
    <script src="wechat-auth-modal.js"></script>
    <!-- 自定义 Tailwind 配置 -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#1677ff', // 主色调，类似截图中的蓝色
                        lightBg: '#f5f7fa', // 浅背景色
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif'],
                    },
                },
            }
        }
    </script>
    <!-- 自定义工具类 -->
    <style>
        .content-auto {
            content-visibility: auto;
        }

        .sidebar-item {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            padding: 0.75rem 1rem;
            border-radius: 0.375rem;
            cursor: pointer;
            transition: all 200ms;
        }

        .sidebar-item.active {
            background-color: #3b82f6;
            color: white;
        }

        .wechat-account-card {
            transition: all 0.3s ease;
        }

        .wechat-account-card:hover {
            transform: translateY(-2px);
        }

        .auth-badge {
            position: absolute;
            top: 0;
            right: 0;
            border-radius: 50%;
            padding: 4px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }

        .auth-badge-active {
            background-color: #10b981;
        }

        .auth-badge-expired {
            background-color: #f59e0b;
        }

        .auth-badge-canceled {
            background-color: #ef4444;
        }
    </style>
</head>

<body class="bg-lightBg min-h-screen flex">
        <!-- 登录弹窗 HTML -->
        <div id="loginModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden">
            <div class="bg-white rounded-lg shadow-xl p-6 w-full max-w-md">
                <div class="flex justify-between items-center mb-4">
                    <h2 class="text-xl font-bold text-gray-800">用户登录</h2>
                    <button id="closeLoginModalBtn" class="text-gray-500 hover:text-gray-700 focus:outline-none">
                        <i class="fa fa-times text-xl"></i>
                    </button>
                </div>
                <form id="loginForm" class="space-y-4">
                    <div>
                        <label for="loginUsername" class="block text-sm font-medium text-gray-700 mb-1">用户名</label>
                        <input type="text" id="loginUsername" name="username" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500" placeholder="请输入用户名" required>
                    </div>
                    <div>
                        <label for="loginPassword" class="block text-sm font-medium text-gray-700 mb-1">密码</label>
                        <input type="password" id="loginPassword" name="password" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500" placeholder="请输入密码" required>
                    </div>
                    <div class="flex items-center justify-between">
                        <div class="flex items-center">
                            <input type="checkbox" id="rememberMe" name="rememberMe" class="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded">
                            <label for="rememberMe" class="ml-2 block text-sm text-gray-700">记住我</label>
                        </div>
                        <a href="#" class="text-sm text-blue-600 hover:text-blue-800">忘记密码?</a>
                    </div>
                    <button type="submit" class="w-full bg-blue-600 text-white py-2 px-4 rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500">
                        登录
                    </button>
                </form>
            </div>
        </div>
        <!-- 登录弹窗样式 -->
        <style>
            /* 登录按钮样式 */
            .login-button {
                background-color: #1E40AF;
                color: white;
                border: none;
                padding: 0.5rem 1rem;
                border-radius: 0.25rem;
                cursor: pointer;
                transition: background-color 0.2s;
            }
            
            .login-button:hover {
                background-color: #1E3A8A;
            }
            
            /* 侧边栏项样式 */
            .sidebar-item {
                display: flex;
                align-items: center;
                padding: 0.75rem 1rem;
                color: #6B7280;
                transition: all 0.2s;
                border-radius: 0.375rem;
                text-decoration: none;
            }
            
            .sidebar-item:hover {
                background-color: #F3F4F6;
                color: #1F2937;
            }
            
            .sidebar-item.active {
                background-color: #3B82F6;
                color: white;
            }
            
            .sidebar-item i {
                margin-right: 0.5rem;
                width: 1.5rem;
                text-align: center;
            }
        </style>
        <!-- 登录弹窗交互脚本 -->
        <script>
            // 点击登录按钮跳转到登录页面
            document.getElementById('showLoginModalBtn')?.addEventListener('click', function() {
                window.location.href = '/login.html';
            });
            
            // 关闭登录弹窗
            document.getElementById('closeLoginModalBtn')?.addEventListener('click', function() {
                document.getElementById('loginModal').classList.add('hidden');
            });
            
            // 点击弹窗外部关闭弹窗
            document.getElementById('loginModal')?.addEventListener('click', function(e) {
                if (e.target === this) {
                    this.classList.add('hidden');
                }
            });
            
            // 登录表单提交
            document.getElementById('loginForm')?.addEventListener('submit', function(e) {
                e.preventDefault();
                
                const username = document.getElementById('loginUsername').value;
                const password = document.getElementById('loginPassword').value;
                
                if (!username || !password) {
                    alert('用户名和密码不能为空');
                    return;
                }
                
                // 创建URL参数
                const params = new URLSearchParams();
                params.append('username', username);
                params.append('password', password);
                params.append('rememberMe', document.getElementById('rememberMe').checked ? 'on' : 'off');
                
                const loginBtn = this.querySelector('button[type="submit"]');
                loginBtn.disabled = true;
                loginBtn.innerHTML = '<i class="fa fa-spinner fa-spin mr-2"></i> 登录中...';
                
                // 发送登录请求
                fetch('/login', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    },
                    body: params
                })
                    .then(response => response.json())
                    .then(data => {
                        loginBtn.disabled = false;
                        loginBtn.innerHTML = '登录';
                        
                        if (data.code === 0) {
                            // 登录成功，存储登录状态
                            localStorage.setItem('isLoggedIn', 'true');
                            localStorage.setItem('username', username);
                            
                            // 关闭登录弹窗
                            document.getElementById('loginModal').classList.add('hidden');
                            
                            // 更新登录UI
                            updateLoginUI();
                            
                            // 显示成功提示
                            alert('登录成功！');
                        } else {
                            // 登录失败，显示错误信息
                            alert(data.message || '登录失败，请检查用户名和密码');
                        }
                    })
                    .catch(error => {
                        console.error('登录请求失败:', error);
                        loginBtn.disabled = false;
                        loginBtn.innerHTML = '登录';
                        alert('网络错误，请稍后再试');
                    });
            });
            
            // 退出登录功能
            document.getElementById('logoutLink')?.addEventListener('click', function(e) {
                e.preventDefault();
                
                // 先调用后端logout接口
                fetch('/logout', {
                    method: 'GET',
                    credentials: 'same-origin'
                })
                .then(() => {
                    // 清除登录状态
                    localStorage.removeItem('isLoggedIn');
                    localStorage.removeItem('username');
                    
                    // 更新UI显示
                    updateLoginUI();
                    
                    // 显示退出成功提示
                    alert('退出成功！');
                    
                    // 刷新页面以确保完全退出
                    location.reload();
                })
                .catch(error => {
                    console.error('退出登录请求失败:', error);
                    // 即使请求失败，也清除localStorage并更新UI
                    localStorage.removeItem('isLoggedIn');
                    localStorage.removeItem('username');
                    updateLoginUI();
                    alert('已清除本地登录状态！');
                });
            });
            
            // 更新登录UI状态
            async function updateLoginUI() {
                // 更新登录按钮显示
                const loginButton = document.getElementById('showLoginModalBtn');
                
                // 更新退出登录项显示
                const logoutItem = document.querySelector('.logout-item');
                
                // 更新用户名显示
                const usernameDisplay = document.getElementById('usernameDisplay');
                const currentUsername = document.getElementById('currentUsername');
                
                const loginStatus = await checkLoginStatus();
                
                if (loginStatus.isLoggedIn && loginStatus.username) {
                    if (loginButton) {
                        loginButton.style.display = 'none';
                    }
                    if (logoutItem) {
                        logoutItem.classList.remove('hidden');
                    }
                    if (usernameDisplay && currentUsername) {
                        currentUsername.textContent = loginStatus.username;
                        usernameDisplay.classList.remove('hidden');
                    }
                } else {
                    if (loginButton) {
                        loginButton.style.display = 'block';
                    }
                    if (logoutItem) {
                        logoutItem.classList.add('hidden');
                    }
                    if (usernameDisplay) {
                        usernameDisplay.classList.add('hidden');
                    }
                }
            }
            
            // 检查登录状态的函数
            function checkLoginStatus() {
                return new Promise((resolve) => {
                    // 首先检查localStorage中的登录状态
                    const localStorageLoggedIn = localStorage.getItem('isLoggedIn');
                    const localStorageUsername = localStorage.getItem('username');

                    if (localStorageLoggedIn === 'true' && localStorageUsername) {
                        // 即使localStorage中有登录状态，也需要向服务器验证
                        fetch('/check-login')
                            .then(response => response.json())
                            .then(data => {
                                if (data.code === 0 && data.isLoggedIn) {
                                    // 服务器验证通过，确认登录状态
                                    resolve({ isLoggedIn: true, username: data.username || localStorageUsername });
                                } else {
                                    // 服务器验证失败，清除localStorage
                                    localStorage.removeItem('isLoggedIn');
                                    localStorage.removeItem('username');
                                    resolve({ isLoggedIn: false, username: null });
                                }
                            })
                            .catch(error => {
                                console.error('验证登录状态失败:', error);
                                // 请求失败时，不应该信任localStorage，返回未登录状态
                                // 清除localStorage中的登录信息
                                localStorage.removeItem('isLoggedIn');
                                localStorage.removeItem('username');
                                resolve({ isLoggedIn: false, username: null });
                            });
                    } else {
                        // localStorage中没有登录状态，返回未登录
                        resolve({ isLoggedIn: false, username: null });
                    }
                });
            }
            
            // 页面加载时检查登录状态
            document.addEventListener('DOMContentLoaded', function() {
                updateLoginUI();
            });
        </script>
    <!-- 侧边栏 -->
    <aside class="w-64 bg-white shadow-md">
        <div class="p-4">
            <h1 class="text-2xl font-bold text-gray-800">会员中心</h1>
            <!-- 登录按钮 -->
            <button id="showLoginModalBtn" class="login-button w-full mt-4">
                <i class="fa fa-sign-in mr-2"></i> 立即登录
            </button>
            <!-- 用户名显示 -->
            <div id="usernameDisplay" class="mt-3 text-center text-gray-600 hidden">
                <i class="fa fa-user-circle mr-1"></i>
                <span id="currentUsername"></span>
            </div>
        </div>
        <nav class="mt-4">
            <ul>
                <li>
                    <a href="index.html" class="sidebar-item">
                        <i class="fa fa-cloud-upload"></i>
                        上传文档
                    </a>
                </li>
                <!-- 新增：文档管理 菜单项 -->
                <li>
                    <a href="documents.html" class="sidebar-item" id="documentsLink">
                        <i class="fa fa-folder-open"></i> <!-- 使用文件夹打开图标，与文档管理语义匹配 -->
                        文档管理
                    </a>
                </li>
                <!-- 新增：公众号管理 菜单项 -->
                <li>
                    <a href="wechat-accounts.html" class="sidebar-item active">
                        <i class="fa fa-weixin"></i>
                        公众号管理
                    </a>
                </li>
                <!-- 新增：账号管理 菜单项 -->
                <li>
                    <a href="wechat-account-management.html" class="sidebar-item">
                        <i class="fa fa-user-circle-o"></i>
                        账号管理
                    </a>
                </li>
                <!-- 新增：抓取管理 菜单项 -->
                <li>
                    <a href="scraping.html" class="sidebar-item">
                        <i class="fa fa-scissors"></i>
                        抓取管理
                    </a>
                </li>
                <!-- 新增：数据库配置 菜单项 -->
                <li>
                    <a href="database-config.html" class="sidebar-item">
                        <i class="fa fa-database"></i>
                        数据库配置
                    </a>
                </li>
                <!-- 新增：发布管理 菜单项 -->
                <li>
                    <a href="publish-management.html" class="sidebar-item">
                        <i class="fa fa-paper-plane"></i>
                        发布管理
                    </a>
                </li>
                <li class="logout-item hidden">
                    <a href="#" class="sidebar-item" id="logoutLink">
                        <i class="fa fa-sign-out"></i>
                        退出登录
                    </a>
                </li>
            </ul>
        </nav>
    </aside>

    <!-- 主内容区 -->
    <main class="flex-1 p-8">
        <div class="bg-white rounded-lg shadow-sm p-6">
            <div class="flex justify-between items-center mb-6">
                <h2 class="text-xl font-semibold text-gray-800">公众号管理</h2>
                <button id="addWechatAccountBtn" class="bg-green-500 hover:bg-green-600 text-white px-4 py-2 rounded-md transition-colors flex items-center">
                    <i class="fa fa-plus mr-2"></i>
                    新增公众号
                </button>
            </div>

            <!-- 公众号列表 -->
            <div id="wechatAccountsList" class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
                <div class="col-span-full text-center text-gray-500 py-16">
                    <i class="fa fa-spinner fa-spin mr-2 text-green-500 text-3xl"></i>
                    <span class="text-gray-600 text-lg">正在加载已授权公众号...</span>
                </div>
            </div>
        </div>
    </main>

    <script>
        // 加载公众号列表
        function loadWechatAccounts() {
            const accountsList = $('#wechatAccountsList');
            accountsList.empty();

            // 模拟加载中状态
            accountsList.append(`
                <div class="col-span-full text-center text-gray-500 py-16">
                    <i class="fa fa-spinner fa-spin mr-2 text-green-500 text-3xl"></i>
                    <span class="text-gray-600 text-lg">正在加载已授权公众号...</span>
                </div>
            `);

            // 先调用checkLoginStatus获取最新的登录状态
            checkLoginStatus().then(loginStatus => {
                const username = loginStatus.username || 'unknown';
                   
                console.log(`loadWechatAccounts: 用户名=${username}`);

                // 从后端API获取真实数据，不再传递userId参数（后端直接从session获取）
                $.ajax({
                    url: '/api/documents/wechat/accounts',
                    type: 'GET',
                    success: function (response) {
                        accountsList.empty();
                        if (response.code === 0 && response.data) {
                            if (response.data.length > 0) {
                                // 渲染公众号卡片
                                response.data.forEach(account => {
                                    console.log('原始公众号数据:', account);

                                    // 进行字段映射，确保前端代码能正确访问字段
                                    // 根据后端返回的实际数据格式进行映射
                                    const mappedAccount = {
                                        id: account.id || '',
                                        nickname: account.account_name || account.nickname || '未知公众号',
                                        headImgUrl: account.head_img_url || 'https://via.placeholder.com/100?text=No+Image',
                                        authorizerAppid: account.appid || '',
                                        serviceTypeInfo: account.account_type || 0,
                                        status: account.auth_status || 1
                                    };

                                console.log('映射后的公众号数据:', mappedAccount);

                                const accountHtml = `
                                    <div class="wechat-account-card bg-white p-5 rounded-xl shadow hover:shadow-lg border border-gray-200" 
                                         data-account-id="${mappedAccount.id}">
                                        <div class="flex items-center justify-between">
                                            <div class="flex items-center">
                                                <div class="relative">
                                                    <img src="${mappedAccount.headImgUrl}" alt="${mappedAccount.nickname}" class="w-16 h-16 rounded-full mr-4 border border-gray-300 shadow-sm">
                                                    <div class="${getAuthStatusClass(mappedAccount.status)}">
                                                        <svg class="w-4 h-4 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="3" d="M5 13l4 4L19 7"></path>
                                                        </svg>
                                                    </div>
                                                </div>
                                                <div>
                                                    <div class="font-semibold text-gray-800 text-lg">${mappedAccount.nickname}</div>
                                                    <div class="text-sm text-gray-500">${mappedAccount.authorizerAppid}</div>
                                                    <div class="text-xs text-gray-400 mt-1">${getAccountTypeText(mappedAccount.serviceTypeInfo)} | ${getAuthStatusText(mappedAccount.status)}</div>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="mt-4 flex justify-end space-x-2">
                                            <button class="edit-account-btn px-3 py-1 text-sm border border-blue-500 text-blue-500 rounded-md hover:bg-blue-50 transition-colors" data-id="${mappedAccount.id}">
                                                <i class="fa fa-pencil mr-1"></i> 编辑
                                            </button>
                                            <button class="delete-account-btn px-3 py-1 text-sm border border-red-500 text-red-500 rounded-md hover:bg-red-50 transition-colors" data-id="${mappedAccount.id}">
                                                <i class="fa fa-trash mr-1"></i> 删除
                                            </button>
                                        </div>
                                    </div>
                                `;
                                accountsList.append(accountHtml);
                            });
                        } else {
                            // 没有已授权的公众号
                            const emptyHtml = `
                                <div class="col-span-full text-center text-gray-500 py-16">
                                    <i class="fa fa-weixin text-6xl text-green-200 mb-6"></i>
                                    <p class="text-gray-600 text-lg mb-6">暂无已授权的公众号</p>
                                    <button id="addFirstAuthBtn" class="bg-green-500 hover:bg-green-600 text-white px-6 py-3 rounded-lg transition text-lg">
                                        <i class="fa fa-plus mr-2"></i>立即添加公众号
                                    </button>
                                </div>
                            `;
                            accountsList.append(emptyHtml);
                        }
                    } else {
                        // 服务器返回了错误状态码
                        const errorHtml = `
                            <div class="col-span-full text-center text-red-500 py-16">
                                <i class="fa fa-exclamation-circle text-4xl mb-4"></i>
                                <p class="text-gray-600">加载失败，请刷新页面重试</p>
                            </div>
                        `;
                        accountsList.append(errorHtml);
                    }
                },
                error: function (xhr, status, error) {
                    accountsList.empty();
                    console.error('加载公众号列表失败:', {
                        status: status,
                        error: error,
                        statusCode: xhr.status,
                        responseText: xhr.responseText,
                        url: '/api/documents/wechat/accounts'
                    });

                    let errorMessage = '加载失败，请检查网络后重试';
                    if (status === 'timeout') {
                        errorMessage = '网络连接超时，请检查网络后重试';
                    } else if (status === 'error') {
                        if (xhr.status === 404) {
                            errorMessage = 'API接口不存在，请稍后重试';
                        } else if (xhr.status === 500) {
                            errorMessage = '服务器内部错误，请稍后重试';
                        } else {
                            errorMessage = `服务器连接失败 (${xhr.status})，请稍后重试`;
                        }
                    }

                    const errorHtml = `
                        <div class="col-span-full text-center text-red-500 py-16">
                            <i class="fa fa-exclamation-circle text-4xl mb-4"></i>
                            <p class="text-gray-600">${errorMessage}</p>
                            <button id="retryLoadBtn" class="mt-4 px-4 py-2 bg-primary text-white rounded-md hover:bg-primary/90 transition-colors">
                                重试
                            </button>
                        </div>
                    `;
                    accountsList.append(errorHtml);
                }
            });
        });
    }

        // 初始化页面
        document.addEventListener('DOMContentLoaded', function() {
            // 检查登录状态
            checkLoginStatus().then(function(loginStatus) {
                if (loginStatus.isLoggedIn) {
                    // 已登录，加载公众号列表
                    loadWechatAccounts();
                } else {
                    // 未登录，显示登录按钮
                    document.getElementById('showLoginModalBtn').style.display = 'block';
                    const accountsList = document.getElementById('wechatAccountsList');
                    accountsList.innerHTML = '';
                    accountsList.innerHTML = `
                        <div class="col-span-full text-center text-gray-500 py-16">
                            <i class="fa fa-lock text-4xl mb-4"></i>
                            <p class="text-gray-600 mb-4">请先登录以管理您的公众号</p>
                            <button id="loginFirstBtn" class="px-6 py-2 bg-primary text-white rounded-md hover:bg-primary/90 transition-colors">
                                <i class="fa fa-sign-in mr-2"></i>立即登录
                            </button>
                        </div>
                    `;
                }
            });

            // 新增公众号按钮点击事件
            document.getElementById('addWechatAccountBtn').addEventListener('click', function() {
                showAuthQRCodeModal();
            });

            // 委托事件处理
            document.addEventListener('click', function(e) {
                // 首次添加公众号按钮点击事件
                if (e.target.closest('#addFirstAuthBtn')) {
                    showAuthQRCodeModal();
                }

                // 重试加载按钮点击事件
                if (e.target.closest('#retryLoadBtn')) {
                    loadWechatAccounts();
                }

                // 先登录按钮点击事件
                if (e.target.closest('#loginFirstBtn')) {
                    document.getElementById('loginModal').classList.remove('hidden');
                }

                // 删除公众号按钮点击事件
                if (e.target.closest('.delete-account-btn')) {
                    e.stopPropagation();
                    const btn = e.target.closest('.delete-account-btn');
                    const accountId = btn.getAttribute('data-id');
                    const accountName = btn.closest('.wechat-account-card').querySelector('.font-semibold').textContent;
                    
                    if (confirm(`确定要删除公众号 "${accountName}" 吗？\n\n删除后将无法恢复，且所有相关数据将被清空。`)) {
                        // 禁用按钮，防止重复点击
                        btn.disabled = true;
                        btn.innerHTML = '<i class="fa fa-spinner fa-spin mr-1"></i> 删除中...';
                        
                        // 调用后端API删除公众号
                        $.ajax({
                            url: `/api/documents/wechat/accounts/${accountId}`,
                            type: 'DELETE',
                            success: function(response) {
                                if (response.code === 0) {
                                    alert(`公众号 "${accountName}" 删除成功`);
                                    loadWechatAccounts();
                                } else {
                                    alert(`删除失败: ${response.message || '未知错误'}`);
                                }
                            },
                            error: function(xhr, status, error) {
                                console.error('删除公众号失败:', error);
                                alert('删除失败，请稍后重试');
                            },
                            complete: function() {
                                // 恢复按钮状态
                                btn.disabled = false;
                                btn.innerHTML = '<i class="fa fa-trash mr-1"></i> 删除';
                            }
                        });
                    }
                }
                
                // 编辑公众号按钮点击事件
                if (e.target.closest('.edit-account-btn')) {
                    e.stopPropagation();
                    const btn = e.target.closest('.edit-account-btn');
                    const accountId = btn.getAttribute('data-id');
                    const accountCard = btn.closest('.wechat-account-card');
                    const accountName = accountCard.querySelector('.font-semibold').textContent;
                    const accountAppid = accountCard.querySelector('.text-sm.text-gray-500').textContent;
                    
                    // 显示编辑弹窗
                    showEditAccountModal(accountId, accountName, accountAppid);
                }

                // 退出登录按钮点击事件
                if (e.target.closest('#logoutLink')) {
                    e.preventDefault();
                    if (confirm('确定要退出登录吗？')) {
                        // 先调用服务器的退出登录接口
                        fetch('/logout', {
                            method: 'POST'
                        })
                        .then(response => response.json())
                        .catch(error => {
                            console.error('退出登录失败:', error);
                        })
                        .finally(() => {
                            // 无论服务器返回什么结果，都清除localStorage中的登录状态
                            localStorage.removeItem('isLoggedIn');
                            localStorage.removeItem('username');
                            localStorage.removeItem('userId');
                            
                            // 更新登录状态UI
                            updateLoginUI();
                            
                            // 刷新页面以确保完全退出
                            window.location.reload();
                        });
                    }
                }
            });

            // 在页面加载完成后检查登录状态
            updateLoginUI();
        });

        // 显示编辑公众号弹窗
        function showEditAccountModal(accountId, accountName, accountAppid) {
            console.log('显示编辑公众号弹窗，ID:', accountId);
            // 先从服务器获取公众号的完整信息，包括Secret
            $.ajax({
                url: `/api/documents/wechat/accounts/${accountId}`,
                type: 'GET',
                success: function(response) {
                    console.log('获取公众号详情响应:', response);
                    
                    if (response.code === 0 && response.data) {
                        const accountInfo = response.data;
                        console.log('公众号详情数据:', accountInfo);
                        
                        // 移除现有的模态框（如果存在）
                        $('#editAccountModal').remove();
                        
                        // 创建模态框HTML
                        const editModalHtml = `
                            <div id="editAccountModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
                                <div class="bg-white rounded-2xl shadow-2xl w-full max-w-md overflow-hidden transform transition-all scale-95 hover:scale-100 duration-200">
                                    <div class="p-6">
                                        <div class="flex justify-between items-center mb-4">
                                            <h2 class="text-xl font-bold text-gray-800">编辑公众号</h2>
                                            <button id="closeEditModalBtn" class="text-gray-400 hover:text-gray-600 transition">
                                                <i class="fa fa-times text-xl"></i>
                                            </button>
                                        </div>
                                        <form id="editAccountForm">
                                            <input type="hidden" id="editAccountId" value="">
                                            <div class="space-y-4">
                                                <div>
                                                    <label class="block text-gray-700 text-sm font-medium mb-1" for="editAccountName">
                                                        公众号名称
                                                    </label>
                                                    <input id="editAccountName" type="text" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent" placeholder="请输入公众号名称">
                                                </div>
                                                <div>
                                                    <label class="block text-gray-700 text-sm font-medium mb-1" for="editAccountAppid">
                                                        公众号AppID
                                                    </label>
                                                    <input id="editAccountAppid" type="text" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent" placeholder="公众号AppID" readonly>
                                                </div>
                                                <div>
                                                    <label class="block text-gray-700 text-sm font-medium mb-1" for="editAccountSecret">
                                                        公众号Secret
                                                    </label>
                                                    <input id="editAccountSecret" type="text" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent" placeholder="请输入公众号Secret密钥">
                                                </div>
                                            </div>
                                            <div class="mt-6 flex justify-end space-x-3">
                                                <button type="button" id="cancelEditBtn" class="px-4 py-2 bg-gray-200 text-gray-700 rounded-lg hover:bg-gray-300 transition">
                                                    取消
                                                </button>
                                                <button type="submit" id="submitEditBtn" class="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition">
                                                    保存修改
                                                </button>
                                            </div>
                                        </form>
                                    </div>
                                </div>
                            </div>
                        `;
                        
                        // 添加模态框到页面
                        $('body').append(editModalHtml);
                        
                        // 直接打印完整的响应数据，以便更全面地了解后端返回的数据结构
                        console.log('完整的响应数据:', JSON.stringify(response, null, 2));
                        console.log('data字段完整内容:', JSON.stringify(accountInfo, null, 2));
                        
                        // 尝试所有可能的字段名获取Secret，扩展搜索范围
                        let secretValue = '';
                        
                        // 1. 检查直接的secret相关字段
                        if (accountInfo.app_secret) {
                            secretValue = accountInfo.app_secret;
                            console.log('从app_secret字段获取Secret值');
                        } else if (accountInfo.appSecret) {
                            secretValue = accountInfo.appSecret;
                            console.log('从appSecret字段获取Secret值');
                        } else if (accountInfo.secretKey) {
                            secretValue = accountInfo.secretKey;
                            console.log('从secretKey字段获取Secret值');
                        } else if (accountInfo.secret) {
                            secretValue = accountInfo.secret;
                            console.log('从secret字段获取Secret值');
                        } else if (accountInfo.Secret) {
                            secretValue = accountInfo.Secret;
                            console.log('从Secret字段获取Secret值');
                        } else if (accountInfo.AppSecret) {
                            secretValue = accountInfo.AppSecret;
                            console.log('从AppSecret字段获取Secret值');
                        } else if (accountInfo.APP_SECRET) {
                            secretValue = accountInfo.APP_SECRET;
                            console.log('从APP_SECRET字段获取Secret值');
                        } else if (accountInfo.App_Secret) {
                            secretValue = accountInfo.App_Secret;
                            console.log('从App_Secret字段获取Secret值');
                        }
                        
                        // 2. 检查嵌套对象中的secret字段
                        if (!secretValue && accountInfo.authorizerInfo) {
                            if (accountInfo.authorizerInfo.app_secret) {
                                secretValue = accountInfo.authorizerInfo.app_secret;
                                console.log('从authorizerInfo.app_secret字段获取Secret值');
                            } else if (accountInfo.authorizerInfo.appSecret) {
                                secretValue = accountInfo.authorizerInfo.appSecret;
                                console.log('从authorizerInfo.appSecret字段获取Secret值');
                            } else if (accountInfo.authorizerInfo.secret) {
                                secretValue = accountInfo.authorizerInfo.secret;
                                console.log('从authorizerInfo.secret字段获取Secret值');
                            }
                        }
                        
                        // 3. 循环检查所有可能包含secret的字段（不区分大小写）
                        const secretCandidates = {};
                        for (const key in accountInfo) {
                            if (accountInfo.hasOwnProperty(key)) {
                                const lowerKey = key.toLowerCase();
                                if (lowerKey.includes('secret') || lowerKey.includes('app_secret') || 
                                    lowerKey.includes('appsecret') || lowerKey.includes('secretkey')) {
                                    const value = accountInfo[key];
                                    secretCandidates[key] = value ? `[存在，长度${value.length}]` : '空';
                                    
                                    // 如果找到非空值且还没有设置secretValue，则使用它
                                    if (!secretValue && value && typeof value === 'string' && value.length > 0) {
                                        secretValue = value;
                                        console.log(`从自动检测的${key}字段获取Secret值`);
                                    }
                                }
                            }
                        }
                        
                        console.log('所有与secret相关的字段:', secretCandidates);
                        console.log('最终确定的Secret值:', secretValue ? `[存在，长度${secretValue.length}]` : '空');
                        
                        // 获取AppID，优先使用authorizerAppid
                        let appidValue = '';
                        if (accountInfo.authorizerAppid) {
                            appidValue = accountInfo.authorizerAppid;
                            console.log('从authorizerAppid字段获取AppID');
                        } else if (accountInfo.appid) {
                            appidValue = accountInfo.appid;
                            console.log('从appid字段获取AppID');
                        } else if (accountInfo.appId) {
                            appidValue = accountInfo.appId;
                            console.log('从appId字段获取AppID');
                        } else {
                            appidValue = accountAppid;
                            console.log('使用传入的accountAppid作为AppID');
                        }
                        
                        // 获取公众号名称
                        let nameValue = '';
                        if (accountInfo.nickname) {
                            nameValue = accountInfo.nickname;
                            console.log('从nickname字段获取公众号名称');
                        } else if (accountInfo.account_name) {
                            nameValue = accountInfo.account_name;
                            console.log('从account_name字段获取公众号名称');
                        } else {
                            nameValue = accountName;
                            console.log('使用传入的accountName作为公众号名称');
                        }
                        
                        // 详细记录secret值的状态
                        console.log('找到的Secret值:', secretValue ? '已获取: ' + secretValue : '未获取');
                        console.log('Secret值长度:', secretValue ? secretValue.length : 0);
                        console.log('公众号详情字段检测:', {
                            authorizerAppid: accountInfo.authorizerAppid,
                            appid: accountInfo.appid,
                            appId: accountInfo.appId,
                            nickname: accountInfo.nickname,
                            account_name: accountInfo.account_name,
                            app_secret: accountInfo.app_secret,
                            appSecret: accountInfo.appSecret
                        });
                        
                        // 设置表单数据
                        $('#editAccountId').val(accountId);
                        $('#editAccountName').val(nameValue);
                        $('#editAccountAppid').val(appidValue);
                        
                        // 添加一个简单的状态显示元素，方便用户直观看到Secret值是否被正确获取
                        let statusElement = document.getElementById('secretStatusDisplay');
                        if (!statusElement) {
                            statusElement = document.createElement('div');
                            statusElement.id = 'secretStatusDisplay';
                            statusElement.style.cssText = 'position:fixed;top:10px;right:10px;background:black;color:white;padding:10px;border-radius:5px;z-index:9999;font-size:12px;';
                            document.body.appendChild(statusElement);
                        }
                        
                        // 显示Secret值获取状态
                        const secretExists = secretValue && secretValue.length > 0;
                        statusElement.innerHTML = `Secret状态: ${secretExists ? '已获取' : '未获取'}<br>长度: ${secretValue ? secretValue.length : 0}<br>时间: ${new Date().toLocaleTimeString()}`;
                        statusElement.style.backgroundColor = secretExists ? '#4CAF50' : '#F44336';
                        
                        // 直接设置Secret值到输入框，并记录操作
                        console.log('开始设置Secret值到输入框，值:', secretValue);
                        const secretInput = document.getElementById('editAccountSecret');
                        if (secretInput) {
                            // 先清空再设置，确保不会有旧值残留
                            secretInput.value = '';
                            console.log('输入框已清空');
                            secretInput.value = secretValue;
                            console.log('Secret值已直接设置到输入框，当前值长度:', secretInput.value.length);
                            console.log('输入框DOM对象状态:', {
                                value: secretInput.value,
                                hasValue: secretInput.value ? true : false,
                                length: secretInput.value.length
                            });
                        }
                        
                        // 使用jQuery设置一次，确保值被正确应用
                        $('#editAccountSecret').val(secretValue);
                        console.log('使用jQuery设置Secret值完成');
                        
                        // 设置一个延迟确保值已正确渲染
                        setTimeout(() => {
                            const updatedSecretInput = document.getElementById('editAccountSecret');
                            if (updatedSecretInput) {
                                // 再次设置一次，确保值被正确显示
                                updatedSecretInput.value = secretValue;
                                console.log('延迟后重新设置Secret值到输入框，最终值:', updatedSecretInput.value);
                                console.log('最终输入框状态:', {
                                    value: updatedSecretInput.value,
                                    hasValue: updatedSecretInput.value ? true : false,
                                    length: updatedSecretInput.value.length
                                });
                            }
                        }, 200);
                        
                        // 绑定关闭按钮事件
                        $('#closeEditModalBtn, #cancelEditBtn').on('click', function() {
                            $('#editAccountModal').remove();
                        });
                        
                        // 提交编辑表单
                        $('#editAccountForm').on('submit', function(e) {
                            e.preventDefault();
                            
                            const accountId = $('#editAccountId').val();
                            const accountName = $('#editAccountName').val().trim();
                            
                            if (!accountName) {
                                alert('公众号名称不能为空');
                                return;
                            }
                            
                            const submitBtn = $('#submitEditBtn');
                            submitBtn.prop('disabled', true);
                            submitBtn.html('<i class="fa fa-spinner fa-spin mr-1"></i> 保存中...');
                            
                            // 调用后端API更新公众号信息
                            $.ajax({
                                url: `/api/documents/wechat/accounts/${accountId}`,
                                type: 'POST',
                                contentType: 'application/json',
                                data: JSON.stringify({
                                    accountName: accountName,
                                    secretKey: $('#editAccountSecret').val().trim()
                                }),
                                success: function(response) {
                                    if (response.code === 0) {
                                        alert('公众号信息更新成功');
                                        $('#editAccountModal').remove();
                                        loadWechatAccounts();
                                    } else {
                                        alert(`更新失败: ${response.message || '未知错误'}`);
                                    }
                                },
                                error: function(xhr, status, error) {
                                    console.error('更新公众号信息失败:', error);
                                    alert('更新失败，请稍后重试');
                                },
                                complete: function() {
                                    submitBtn.prop('disabled', false);
                                    submitBtn.html('保存修改');
                                }
                            });
                        });
                    } else {
                        alert('获取公众号信息失败：' + (response.message || '未知错误'));
                    }
                },
                error: function(xhr, status, error) {
                    console.error('获取公众号信息失败:', error);
                    alert('获取公众号信息失败，请稍后重试');
                }
            });
        }
        
        // 检查登录状态的函数
        function checkLoginStatus() {
            return new Promise((resolve) => {
                console.log('checkLoginStatus: 开始检查登录状态');
                 
                // 首先检查localStorage中的登录状态
                const localStorageLoggedIn = localStorage.getItem('isLoggedIn');
                const localStorageUsername = localStorage.getItem('username');
                 
                console.log(`checkLoginStatus: localStorage信息 - 登录状态=${localStorageLoggedIn}, 用户名=${localStorageUsername}`);

                if (localStorageLoggedIn === 'true' && localStorageUsername) {
                    // 返回登录状态，只包含用户名（后端直接从session获取userId）
                    resolve({ isLoggedIn: true, username: localStorageUsername });
                    return;
                }

                // 否则返回未登录状态，清除可能存在的userId
                console.log('checkLoginStatus: 用户未登录');
                localStorage.removeItem('userId');
                resolve({ isLoggedIn: false, username: null, userId: null });
            });
        }
    </script>
</body>

</html>